package com.iven.xie.code.generator.controller;

import com.iven.xie.code.generator.bean.PageList;
import com.iven.xie.code.generator.bean.QueryBean;
import com.iven.xie.code.generator.bean.ResObject;
import com.iven.xie.code.generator.service.CodeGeneratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器
 *
 * @author iven.xie
 */
@Api(tags = "代码生成器信息接口")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/code/generator")
@Slf4j
public class CodeGeneratorController {
    @Autowired
    private CodeGeneratorService codeGeneratorService;

    /**
     * 列表
     */
    @ResponseBody
    @ApiOperation(value = "查询列表", notes = "查询列表")
    @GetMapping("/list")
    public ResObject list(@RequestParam Map<String, Object> params) {
        PageList pageList = codeGeneratorService.queryList(new QueryBean(params));
        return ResObject.success(pageList);
    }

    @ResponseBody
    @ApiOperation(value = "查询表", notes = "查询表")
    @GetMapping("/table")
    public ResObject table(@RequestParam String tableName) {
        Map<String, String> dataMap = codeGeneratorService.queryTable(tableName);
        return ResObject.success(dataMap);
    }

    @ResponseBody
    @ApiOperation(value = "查询表列", notes = "查询表列")
    @GetMapping("/columns")
    public ResObject columns(@RequestParam String tableName) {
        List<Map<String, String>> dataList = codeGeneratorService.queryColumns(tableName);
        return ResObject.success(dataList);
    }

    /**
     * 生成代码
     */
    @ApiOperation(value = "生成代码", notes = "生成代码")
    @GetMapping("/code")
    public void code(String tables, HttpServletResponse response) throws IOException {
        byte[] data = codeGeneratorService.generatorCode(tables.split(","));

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"iven.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }
}
